﻿using System;
using System.IO;
using System.Management;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Text;

namespace SolfWareRegister
{
   
    public static class RegHelper
    {
        public static bool IsRegisted = false;
        private static string ProductionName = "PowerVisual";
        private static string softWareName = "DataServer";
        public static bool CheckRegisteState()
        {
            string msgString = "";
            string strSerial = (Computer.CurrentIns.AuthSerialID + Computer.CurrentIns.PostFix).GetHashCode().ToString();
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] palindata = Encoding.Default.GetBytes(strSerial);//将要加密的字符串转换为字节数组
            byte[] encryptdata = md5.ComputeHash(palindata);//将字符串加密后也转换为字符数组
            msgString = Convert.ToBase64String(encryptdata);//将加密后的字节数组转换为加密字符串
            try
            {
                Microsoft.Win32.RegistryKey retkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("software", true).OpenSubKey(ProductionName).OpenSubKey("checkid");
                if (msgString == (string)retkey.GetValue(softWareName))
                {
                    IsRegisted = true;
                    return true;
                }
            }
            catch 
            {
                IsRegisted = false;
                return false;
            }
            IsRegisted = false;
            return false;
        }

        public static void RegisteSolfware(string strSerial)
        {
            if (!string.IsNullOrEmpty(strSerial)) 
            {
                Microsoft.Win32.RegistryKey retkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("software", true).CreateSubKey(ProductionName).CreateSubKey("checkid");
                retkey.SetValue(softWareName, strSerial);
                if (CheckRegisteState())
                {
                    MessageBox.Show("注册成功"); 
                } 
                else
                {
                    MessageBox.Show("注册码错误!"); 
                }
            } 
            else 
            { 
                MessageBox.Show("注册码错误"); 
            }
        }
        /// <summary>
        /// 给其他PC注册
        /// </summary>
        /// <param name="solfwareName"></param>
        /// <param name="strSerial">(Computer.CurrentIns.CpuID + "2015").GetHashCode().ToString();</param>
        public static string GenerateSerial(string strSerial)
        {
            string msgString = "12";
            if (!string.IsNullOrEmpty(strSerial))
            {
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] palindata = Encoding.Default.GetBytes(strSerial);//将要加密的字符串转换为字节数组
                byte[] encryptdata = md5.ComputeHash(palindata);//将字符串加密后也转换为字符数组
                msgString = Convert.ToBase64String(encryptdata);//将加密后的字节数组转换为加密字符串
                return msgString;
            }
            else
            {
                MessageBox.Show("注册码错误");
                return "";
            }
        }
        private static byte[] _keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
        public static string EncryptDES(string encryptString, string encryptKey)
        {
            if (string.IsNullOrEmpty(encryptString))
            {
                return null;
            }
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
                byte[] rgbIV = _keys;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }
        public static string DecryptDES(string decryptString, string decryptKey)
        {
            if (string.IsNullOrEmpty(decryptString))
            {
                return "";
            }
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
                byte[] rgbIV = _keys;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return decryptString;
            }
        }
        public static string GenerateExpireCode(DateTime expireTime)
        {
           return EncryptDES(expireTime.ToString("yyyy-MM-dd HH:mm:ss"), "02220125"); ;
        }

        public static DateTime DESstringToDateTime(this string strDate)
        {
            string str = DecryptDES(strDate, "02220125");
            DateTime date;
            DateTime.TryParse(str, out date);
            return date;
        }
    }

    /// <summary>
    /// 计算机信息类
    /// </summary>
    public class Computer
    {
        public string PostFix = "Visual2020";
        public string AuthSerialID;
        public string CpuID;
        public string MacAddress;
        public string DiskID;
        public string IpAddress;
        public string LoginUserName;
        public string ComputerName;
        public string SystemType;
        public string TotalPhysicalMemory; //单位：M
        private static Computer _instance;

        public static Computer CurrentIns
        {
            get 
            {
                if (_instance == null)
                    _instance = new Computer();
                return Computer._instance; 
            }
            set { Computer._instance = value; }
        }
        internal Computer()
        {
            CpuID = GetCpuID();
            MacAddress = GetMacAddress();
            DiskID = GetDiskID();
            AuthSerialID = CpuID + MacAddress + DiskID;
            //IpAddress = GetIPAddress();
            //LoginUserName = GetUserName();
            //SystemType = GetSystemType();
            //TotalPhysicalMemory = GetTotalPhysicalMemory();
            //ComputerName = GetComputerName();
        }
        
        string GetCpuID()
        {
            try
            {
                //获取CPU序列号代码
                string cpuInfo = "";//cpu序列号
                ManagementClass mc = new ManagementClass("Win32_Processor");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
                }
                moc = null;
                mc = null;
                return cpuInfo;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }
        string GetMacAddress()
        {
            try
            {
                //获取网卡硬件地址
                string mac = "";
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        mac = mo["MacAddress"].ToString();
                        break;
                    }
                }
                moc = null;
                mc = null;
                return mac;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }
        string GetIPAddress()
        {
            try
            {
                //获取IP地址
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        //st=mo["IpAddress"].ToString();
                        System.Array ar;
                        ar = (System.Array)(mo.Properties["IpAddress"].Value);
                        st = ar.GetValue(0).ToString();
                        break;
                    }
                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }
        string GetDiskID()
        {
            try
            {
                //获取硬盘ID
                String HDid = "";
                ManagementClass mc = new ManagementClass("Win32_DiskDrive");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    HDid = (string)mo.Properties["Model"].Value;
                }
                moc = null;
                mc = null;
                return HDid;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }
        /// <summary>
        /// 操作系统的登录用户名
        /// </summary>
        /// <returns></returns>
        string GetUserName()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    st = mo["UserName"].ToString();
                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }

        /// <summary>
        /// PC类型
        /// </summary>
        /// <returns></returns>
        string GetSystemType()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    st = mo["SystemType"].ToString();
                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }
        /// <summary>
        /// 物理内存
        /// </summary>
        /// <returns></returns>
        string GetTotalPhysicalMemory()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    st = mo["TotalPhysicalMemory"].ToString();
                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }
        /// <summary>
        ///  获取计算机名称
        /// </summary>
        /// <returns></returns>
        string GetComputerName()
        {
            try
            {
                return System.Environment.GetEnvironmentVariable("ComputerName");
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }
    }
}
